<?php

use Drupal\wx_pay\Entity\WxPayTransaction;
use Drupal\wx_pay_refund\WxPayRefundController;

function wx_pay_refund_refund_form($form, &$form_state, WxPayTransaction $wxPayTransaction) {
  $form_state['wxPayTransaction'] = $wxPayTransaction;

  $form['refund_fee'] = [
    '#title' => t('退款金额'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#element_validate' => [
      'element_validate_number',
      'wx_pay_refund_validate_refund_fee',
    ],
    '#description' => t('需要退款的金额（单位：元），如果超过支付的金额则全额退款'),
  ];
  $form['refund_desc'] = [
    '#title' => t('退款原因'),
    '#type' => 'textarea',
    '#description' => t('如果预订失败，请输入原因。'),
    '#required' => TRUE,
  ];

  $form['actions'] = [
    '#type' => 'actions',
  ];
  $form['actions']['delete'] = [
    '#type' => 'submit',
    '#value' => t('确定退款'),
    '#submit' => ['wx_pay_refund_refund_form_submit_refund'],
  ];
  $form['actions']['cancel'] = [
    '#type' => 'submit',
    '#value' => t('取消'),
  ];
  return $form;
}

function wx_pay_refund_validate_refund_fee($element, &$form_state) {
  $value = $element['#value'];
  if ($value != '' && $value <= 0) {
    form_error($element, t('请输入正确的退款金额.'));
  }
}

function wx_pay_refund_refund_form_submit_refund($form, $form_state) {
  $wxPayTransaction = $form_state['wxPayTransaction'];
  if ($wxPayTransaction instanceof WxPayTransaction) {
    $wxPayRefundController = new WxPayRefundController();
    $refund_fee = $form_state['values']['refund_fee'];
    $refund_fee = $refund_fee * 100;
    $refund_desc = $form_state['values']['refund_desc'];
    $refund = $wxPayRefundController->refundTransaction('common', $wxPayTransaction, $refund_fee, $refund_desc);
    if ($refund->result_code == 'SUCCESS') {
      drupal_set_message('退款成功');
    }
    else {
      drupal_set_message($refund->err_code_des, 'warning');
    }
  }
}
